package ru.compscicenter.uno.wizard;

import ru.compscicenter.uno.GameSettings;
import ru.compscicenter.uno.Main_wizard;
import ru.compscicenter.uno.model.Rules;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * User: SLeeP
 * Date: 07.03.12
 * Time: 4:55
 */
public class Panel2ServerRulesDescriptor extends WizardPanelDescriptor implements ActionListener, DocumentListener {
    public static final String IDENTIFIER = "SERVER_RULES";
    private String next;
    private Panel2ServerRules panel2ServerRules;
    private GameSettings gameSettings;

    public Panel2ServerRulesDescriptor(GameSettings gameSettings) {
        this.gameSettings = gameSettings;
        panel2ServerRules = new Panel2ServerRules();
        panel2ServerRules.addRuleListener(this);
        panel2ServerRules.addDocumentListener(this);
        setPanelDescriptorIdentifier(IDENTIFIER);
        setPanelComponent(panel2ServerRules);
    }

    public Object getNextPanelDescriptor() {
        return Panel3ServerWaitDescriptor.IDENTIFIER;
    }

    public Object getBackPanelDescriptor() {
        return Panel1Descriptor.IDENTIFIER;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String actionCommand = e.getActionCommand();
        panel2ServerRules.updateRules(Rules.Rule.valueOf(actionCommand));
        gameSettings.serverController.setRules(getRules());
    }
    
    public Rules getRules() {
        return panel2ServerRules.getRules();
    }

    private void doUpdate() {
        try {
            String str = Panel2ServerRules.pointsToWinText.getText();
            if (str.length() == 0) {
                getWizard().setNextFinishButtonEnabled(false);
            } else {
                Panel2ServerRules.rules.setPointsToWin(Integer.parseInt(str));
                getWizard().setNextFinishButtonEnabled(true);
                gameSettings.serverController.setRules(getRules());
            }
        } catch (NumberFormatException ex) {
            getWizard().setNextFinishButtonEnabled(false);
        }
    }
    @Override
    public void insertUpdate(DocumentEvent e) {
        doUpdate();
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        doUpdate();
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        doUpdate();
    }
}
